package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //redis的key
        String redisKey = "follows:" + userId;
        //判断当前用户和关注用户是否是同一人
        if (userId.equals(followUserId)) {
            return Result.fail("不能关注或取关自己！");
        }
        //准备查询条件
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<Follow>()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, followUserId);
        //1.判断到底是关注还是取关
        if (isFollow) {
            //2.判断是否已经关注过该用户
            Boolean isMember = stringRedisTemplate.opsForSet().isMember(redisKey, followUserId.toString());
            if (BooleanUtil.isTrue(isMember)) {
                return Result.fail("你已经关注过该用户了！");
            }
            //3.关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean success = save(follow);
            if (success) {
                //把关注的用户id，放入redis的set集合
                //sadd userId followerUserId
                stringRedisTemplate.opsForSet().add(redisKey, followUserId.toString());
            }
        } else {
            //4.取关，删除数据 delete from tb_follow where userId = ? and followUserId = ?
            boolean success = remove(queryWrapper);
            if (success) {
                //把关注用户的id从redis集合中移除
                stringRedisTemplate.opsForZSet().remove(redisKey, followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //1.查询是否关注
        Integer count = lambdaQuery()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, followUserId).count();
        //2.判断
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long targetUserId) {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        if (userId.equals(targetUserId)) {
            return Result.fail("不能查询自己的共同关注！");
        }
        //当前用户关注的key
        String userKey = "follows:" + userId;
        //目标用户关注的key
        String targetUserKey = "follows:" + targetUserId;
        //2.求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(userKey, targetUserKey);
        if (CollectionUtil.isEmpty(intersect)) {
            return Result.ok(Collections.emptyList());
        }
        //3.解析id集合
        List<Long> commonUserIds = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        //4.查询用户
        List<User> commonUsers = userService.listByIds(commonUserIds);
        List<UserDTO> userDTOS = BeanUtil.copyToList(commonUsers, UserDTO.class);
        return Result.ok(userDTOS);
    }
}
